1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
| class HexToc {
constructor(bitValueArrayLength, singleBitLength, config) {
const defaultConfig = {
reverse: false,
noPrefix: false,
separator: "" }
this.bitValueArray = [0];
this.singleBitLength = 2;
this.config = { ...defaultConfig, ...config };
if (typeof bitValueArrayLength === "number" && bitValueArrayLength > 0) { this.#resizeBitValueArray(bitValueArrayLength); }
if (typeof singleBitLength === "number" && singleBitLength > 0) { this.singleBitLength = singleBitLength; } }
#resizeBitValueArray(length) { const increment = length - this.bitValueArray.length; if (increment < 0) { console.error("不能缩减 bitValueArray 长度"); return; } for (let i = 0; i < increment; i++) { this.bitValueArray.push(0); } }
#convertDecToHex(dec) { if (typeof dec !== "number") { console.error("参数 dec 必须为数值类型"); return; } return dec.toString(16).padStart(this.singleBitLength, "0").slice(-this.singleBitLength).toUpperCase(); }
toString() { let res = ""; for (const dec of this.bitValueArray) { res = this.config.reverse ? `${res}${this.config.separator}${this.#convertDecToHex(dec)}` : `${this.#convertDecToHex(dec)}${this.config.separator}${res}`; } return this.config.noPrefix ? res : `0x${res}`; }
getRawData() { return this.bitValueArray; }
setBitValueByArrayIndex(arrayIndex, dec) { if (arrayIndex < 0) { console.error("arrayIndex 不能小于 0"); return; } if (arrayIndex > this.bitValueArray.length) { console.error("arrayIndex 不能大于 bitValueArray 长度"); return; } this.bitValueArray[arrayIndex] = dec; return this; }
setBitValueByTocDepth(tocDepth, dec) { if (tocDepth - 1 < 0) { console.error("tocDepth - 1 不能小于 0\n或许你应该使用 setBitValueByArrayIndex() ?"); return; } if (tocDepth - 1 > this.bitValueArray.length) { console.error("tocDepth - 1 不能大于 bitValueArray 长度"); return; } this.bitValueArray[tocDepth - 1] = dec; return this; }
setBitValueArray(decArray) { for (let i = 0; i < decArray.length; i++) { this.bitValueArray[i] = decArray[i]; } return this; } }
|